<?php
declare (strict_types = 1);

namespace app\api\model;

use think\Model;

class SysFile extends Model
{
    // 设置表名
    protected $name = 'sys_file';
    
    // 设置主键
    protected $pk = 'id';

    // 自动写入时间戳
    protected $autoWriteTimestamp = false;

    // 类型转换
    protected $type = [
        'id'              => 'integer',
        'group_id'        => 'integer',
        'file_size'       => 'integer',
        'width'           => 'integer',
        'height'          => 'integer',
        'create_time'     => 'datetime',
        'update_time'     => 'datetime',
    ];

    /**
     * 获取文件URL
     * @return string
     */
    public function getFileUrlAttr(): string
    {
        if (empty($this->dir) || empty($this->file_name)) {
            return '';
        }
        return  'https://sanyanhu.oss-cn-shenzhen.aliyuncs.com/' . $this->file_name;
    }

    /**
     * 获取文件列表
     * @param int $page
     * @param int $limit
     * @return array
     */
    public static function getList(int $page = 1, int $limit = 10): array
    {
        $query = self::where('del_flag', '0')
            ->order('create_time', 'desc');

        $total = $query->count();
        $list = $query->page($page, $limit)->select();

        $data = [];
        foreach ($list as $item) {
            $data[] = [
                'id' => $item->id,
                'file_name' => $item->file_name,
                'original' => $item->original,
                'type' => $item->type,
                'file_size' => $item->file_size,
                'create_time' => $item->create_time,
                'file_url' => $item->file_url
            ];
        }

        return [
            'total' => $total,
            'list' => $data,
            'page' => $page,
            'limit' => $limit
        ];
    }
} 